package com.zhiying.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhiying.domain.Role;
import com.zhiying.domain.RoleMenu;
import com.zhiying.mybatis.RoleMenuMapper;
import com.zhiying.mybatis.UserRoleMapper;
import com.zhiying.service.IRoleService;


@Service
public class RolesServiceImpl  implements IRoleService {

	@Autowired
	private RoleMenuMapper roleMenuMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;



	@Override
	public Integer updateRole(Role role, String[] menuIds, String userName) {
		//更新用户信息
		role.setUpdateBy(userName);
		role.setUpdateTime(new Date());
		Integer count = userRoleMapper.updateById(role);

		//先删除该用户授权信息
		RoleMenu queryRoleMenu = new RoleMenu();
		queryRoleMenu.setRoleId(role.getRoleId());
		userRoleMapper.delete(queryRoleMenu);

		//遍历循环,插入角色目录表记录
		if (menuIds != null && menuIds.length > 0) {
			List<RoleMenu> roleMenus = new ArrayList<>();
			for (int i = 0; i < menuIds.length; i++) {
				RoleMenu roleMenu = new RoleMenu();
				roleMenu.setMenuId(Long.valueOf(menuIds[i]));
				roleMenu.setRoleId(role.getRoleId());
				roleMenu.setCreateBy(userName);
				roleMenu.setCreateTime(new Date());
				roleMenus.add(roleMenu);
			}
			roleMenuMapper.insertRoleMenus(roleMenus);
		}
		return count;
	}



	@Override
	public Integer createRole(Role role, String[] menuIds, String userName) {
		//遍历循环,插入角色目录表记录
		role.setUpdateBy(userName);
		role.setUpdateTime(new Date());
		int count=roleMenuMapper.createRole(role);
		int maxroleId=selectMaxId();
		if (menuIds != null && menuIds.length > 0) {
			List<RoleMenu> roleMenus = new ArrayList<>();
			for (int i = 0; i < menuIds.length; i++) {
				RoleMenu roleMenu = new RoleMenu();
				roleMenu.setMenuId(Long.valueOf(menuIds[i]));
				roleMenu.setRoleId(Long.valueOf(maxroleId));
				roleMenu.setCreateBy(userName);
				roleMenu.setCreateTime(new Date());
				roleMenus.add(roleMenu);
			}
			roleMenuMapper.insertRoleMenus(roleMenus);
		}
		return count;
	}



	@Override
	public int selectMaxId() {
		// TODO Auto-generated method stub
		return roleMenuMapper.selectMaxId();
	}


}
